<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8" style="margin-bottom:30px">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['drug:warehousing:add']"
        >新增入库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['drug:warehousing:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="审核状态" prop="auditStatus" >
        <el-select v-model="queryParams.auditStatus" placeholder="审核状态" clearable style="width: 100px">
          <el-option label="未审核" value='0' />
          <el-option label="审核通过" value='1' />
          <el-option label="审核未通过" value='2' />
        </el-select>
      </el-form-item>
      <el-form-item label="入库类型" prop="warehousingType">
        <el-select v-model="queryParams.warehousingType" placeholder="入库类型" clearable style="width: 100px">
          <el-option label="采购入库" value='采购入库' />
          <el-option label="退货入库" value='退货入库' />
          <el-option label="其他入库" value='其他入库' />
        </el-select>
      </el-form-item>
      <el-form-item label="入库日期" style="width: 308px">
        <el-date-picker
          v-model="daterangeWarehousingDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="入库单号" prop="warehousingOrderId">
        <el-input
          v-model="queryParams.warehousingOrderId"
          placeholder="请输入入库单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-table v-loading="loading" :data="warehousingList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="序号" align="center" prop="id" width="55" />
      <el-table-column label="入库单号" align="center" prop="warehousingOrderId" />
      <el-table-column label="入库人员" align="center" prop="warehousingStaff">
        <template #default="scope">
          {{userList.find(item => item.userId == scope.row.warehousingStaff)?.nickName || '未知' }}
          <!-- <dict-tag :options="userList" :value="scope.row.warehousingStaff"/> -->
        </template>
      </el-table-column>
      <el-table-column label="入库类型" align="center" prop="warehousingType"/>
      <el-table-column label="供应商" align="center" prop="supplier">
        <template #default="scope">
          <dict-tag :options="doctor_drug_manufacturer" :value="scope.row.supplier"/>
        </template>
      </el-table-column>
      <el-table-column label="制单日期" align="center" prop="documentCreationDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.documentCreationDate, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="制单人员" align="center" prop="documentCreationStaff" />
      <el-table-column label="采购金额" align="center" prop="totalPurchaseAmount" />
      <el-table-column label="零售金额" align="center" prop="totalRetailAmount" />
      <el-table-column label="审核状态" align="center" prop="auditStatus" width="120">
        <template #default="scope">
          <!-- <dict-tag :options="doctor_drug_category" :value="scope.row.auditStatus"/> -->
          <el-tag v-if="scope.row.auditStatus == '0'" type="warning">未审核</el-tag>
          <el-tag v-if="scope.row.auditStatus == '1'" type="success">审核通过</el-tag>
          <el-tag v-if="scope.row.auditStatus == '2'" type="danger">审核未通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  width="150">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['drug:warehousing:edit']" v-if="scope.row.auditStatus == '0'">审核</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['drug:warehousing:edit']" v-if="scope.row.auditStatus == '1'">查看详细</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['drug:warehousing:edit']" v-if="scope.row.auditStatus == '2'">未通过</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['drug:warehousing:remove']"  v-if="scope.row.auditStatus == '2' || scope.row.auditStatus == '0' " >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改药品入库对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="warehousingRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="入库单号" prop="warehousingOrderId">
          <el-input v-model="form.warehousingOrderId" placeholder="请输入入库单号" />
        </el-form-item>
        <el-form-item label="入库日期" prop="warehousingDate">
          <el-date-picker clearable
            v-model="form.warehousingDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择入库日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="入库人员" prop="warehousingStaff">
          <el-select v-model="form.warehousingStaff" placeholder="请选择入库人员">
            <el-option
              v-for="dict in doctor_drug_category"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入库类型" prop="warehousingType">
          <el-select v-model="form.warehousingType" placeholder="请选择入库类型">
            <el-option
              v-for="dict in doctor_drug_category"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="supplier">
          <el-select v-model="form.supplier" placeholder="请选择供应商">
            <el-option
              v-for="dict in doctor_drug_category"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="制单日期" prop="documentCreationDate">
          <el-date-picker clearable
            v-model="form.documentCreationDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择制单日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="制单人员" prop="documentCreationStaff">
          <el-input v-model="form.documentCreationStaff" placeholder="请输入制单人员" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="采购金额" prop="totalPurchaseAmount">
          <el-input v-model="form.totalPurchaseAmount" placeholder="请输入采购金额" />
        </el-form-item>
        <el-form-item label="零售金额" prop="totalRetailAmount">
          <el-input v-model="form.totalRetailAmount" placeholder="请输入零售金额" />
        </el-form-item>
        <el-form-item label="审核状态" prop="auditStatus">
          <el-select v-model="form.auditStatus" placeholder="请选择审核状态">
            <el-option
              v-for="dict in doctor_drug_category"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核日期" prop="auditDate">
          <el-date-picker clearable
            v-model="form.auditDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择审核日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核人员" prop="auditStaff">
          <el-input v-model="form.auditStaff" placeholder="请输入审核人员" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Warehousing">
import { listWarehousing, getWarehousing, delWarehousing, addWarehousing, updateWarehousing } from "@/api/drug/warehousing";
import { listUser } from "@/api/system/user";

const { proxy } = getCurrentInstance();
const { doctor_drug_category,doctor_drug_manufacturer} = proxy.useDict('doctor_drug_category','doctor_drug_manufacturer');

const userList = ref([]);
const warehousingList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeWarehousingDate = ref([]);
import useUserStore from '@/store/modules/user'
const user = useUserStore();

import { onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';

const route = useRoute();

watch(
  () => route.query.refresh,
  () => {
    if (route.path === '/1/warehousing') {
      getList();  // 这是Warehousing页面原有的获取列表数据方法
    }
  }
);
getUserList();
/** 查询用户列表 */
function getUserList() {
  loading.value = true;
  listUser({
    pageNum: 1,
    pageSize: 9999,
  }).then(res => {
    userList.value = res.rows;
    console.log(userList.value);
  });
};

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    warehousingOrderId: null,
    warehousingDate: null,
    warehousingType: null,
    auditStatus: null,
  },
  rules: {
    warehousingOrderId: [
      { required: true, message: "入库单号不能为空", trigger: "blur" }
    ],
    warehousingDate: [
      { required: true, message: "入库日期不能为空", trigger: "blur" }
    ],
    warehousingStaff: [
      { required: true, message: "入库人员不能为空", trigger: "change" }
    ],
    warehousingType: [
      { required: true, message: "入库类型不能为空", trigger: "change" }
    ],
    supplier: [
      { required: true, message: "供应商不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);




/** 查询药品入库列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeWarehousingDate && '' != daterangeWarehousingDate) {
    queryParams.value.params["beginWarehousingDate"] = daterangeWarehousingDate.value[0];
    queryParams.value.params["endWarehousingDate"] = daterangeWarehousingDate.value[1];
  }
  listWarehousing(queryParams.value).then(response => {
    warehousingList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    warehousingOrderId: null,
    warehousingDate: null,
    warehousingStaff: null,
    warehousingType: null,
    supplier: null,
    documentCreationDate: null,
    documentCreationStaff: null,
    remarks: null,
    totalPurchaseAmount: null,
    totalRetailAmount: null,
    auditStatus: null,
    auditDate: null,
    auditStaff: null
  };
  proxy.resetForm("warehousingRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeWarehousingDate.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 时间格式化
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}${month}${day}${hours}${minutes}`;
}
// 格式为 YYYY-MM-DD HH:MM:SS 的时间字符串
function formatDateTime(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  // 获取当前的时间 将当前的年月日时分秒时间赋值给
  const now = new Date();
  // 将当前的时间格式化202501010101
  form.value.warehousingOrderId = 'SP'+formatDate(now);
  form.value.documentCreationDate = formatDateTime(now);
  form.value.documentCreationStaff = user.name;
  proxy.$router.push({ 
    path: "/drug/intermediate",
    query: {
      title1: "新增入库信息",
      formData: JSON.stringify(form.value) // 序列化表单数据
    }
   });

}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  form.value=row
  if(row.auditStatus == '1'){
    // 入库详情-审核通过
   
        proxy.$router.push({ 
        path: "/drug/intermediate",
        query: {
          title1: "入库详情-审核通过",
          formData: JSON.stringify(form.value) // 序列化表单数据
        }
      });
  
  }
  if(row.auditStatus == '2'){
      // 入库详情-审核未通过
    
        proxy.$router.push({ 
        path: "/drug/intermediate",
        query: {
          title1: "入库详情-审核未通过",
          formData: JSON.stringify(form.value) // 序列化表单数据
        }
      });
   
  }
  if(row.auditStatus == '0'){
     // 入库详情-审核
   
       
        proxy.$router.push({ 
        path: "/drug/intermediate",
        query: {
          title1: "入库详情-待审核",
          formData: JSON.stringify(form.value) // 序列化表单数据
        }
    
    });
  }
}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["warehousingRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateWarehousing(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addWarehousing(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除药品入库编号为"' + _ids + '"的数据项？').then(function() {
    return delWarehousing(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('drug/warehousing/export', {
    ...queryParams.value
  }, `warehousing_${new Date().getTime()}.xlsx`)
}

getList();
</script>
